/**
 * 1、判断用户是否登录
 * 2、已登录则获取全部的文章
 */

import { getDB } from "~/server/utils/db/mysql";
import {
  getFirstImage,
  getLoginUid,
  responseJson,
  trimMarkdown,
} from "~/server/utils/helper";

export default defineEventHandler(async (event) => {
  //获取数据
  const params = await getQuery(event);

  // 参数验证和默认值
  const page = Number(params.page) || 1;
  const pageSize = Number(params.pageSize) || 8;

  const con = getDB();
  try {
    //获取已发布的文章（state=2 表示已发布）
    const [notesData] = await con.query(
      "SELECT DISTINCT notes.id AS id, notes.title, notes.content_md, notes.uid, notes.created_at, users.nickname FROM `notes` LEFT JOIN `users` ON notes.uid = users.id WHERE notes.`state`=? ORDER BY notes.`id` DESC LIMIT ? OFFSET ?",
      [2, pageSize, (page - 1) * pageSize]
    );
    
    // 确保 notesData 是数组
    const notesList = Array.isArray(notesData) ? notesData : [];
    
    notesList.map((v: any) => {
      v.subTitle = trimMarkdown(v.content_md, 300);
      v.cover = getFirstImage(v.content_md);
      v.like = 45;
      v.content_md = "";
      v.flag = false;
    });

    return responseJson(0, "获取文章成功哦", {
      list: notesList,
    });
  } catch (e) {
    console.error("获取文章列表失败错误详情:", e);
    if (e instanceof Error) {
      console.error("错误消息:", e.message);
      console.error("错误堆栈:", e.stack);
    }
    // @ts-ignore
    setResponseStatus(event, 500);
    return responseJson(1, "服务器错误", {});
  }
  // 注意：不要关闭连接池！连接池应该保持打开状态以供后续使用
  // 连接池会自动管理连接的获取和释放
});
